import {AlertController, IonicPage, NavController, NavParams} from "ionic-angular";
import {Component} from "@angular/core";
import {Storage} from "@ionic/storage";
import {HttpClient} from "@angular/common/http";
import {AppUrl} from "../../../app/app.general";
import {CashdetailPage} from "../business-food-cashdetail/business-food-cashdetail";

@IonicPage()
@Component({
  selector: "page-busifood-tableorder",
  templateUrl: "busifood-tableorder.html",
})

export class BusifoodTableorderPage {
  private tableSite = {
    used: {name: '已开台', color: '#389cf4'},
    waitForClean: {name: '待清理', color: 'brown'},
    ordered: {name: '已预订', color: 'coral'},
    stopToUse: {name: '暂停使用', color: 'black'},
    Idle: {name: '空闲', color: '#41b883'},
    cancel: {name: '取消', color: '#41b883'}
  };


  private floor: number;
  private tableNo: string;
  private tableid:number;
  private sumCount: number;
  private goodname: string;
  private goodprice: number;

  private id: number;

  // private text = {
  //   viewDetail: "查看详情",used: "开台",checkCount: "结账离店",feeAdd: "代理商品购买",
  //   changeRoom: "更换餐台",cleaned: "打扫干净",cancel: "取消",stopToUse: "暂停使用",
  //   recoveryToUser: "恢复使用", roomOrder: "预订餐台",cancelOrder: "取消预订",orderadd: "加菜",
  // };

  private orderTable = {
    id: 0,
    tableNo: '',
    tableSite: {name: '', color: ''},
    goods: {goodname: '', goodprice: 0, sumBuy: 0, sumPrice: 0, isbuy: false},
    sumCount: 0
  };

  private callBack: any;

  private status = [];
  private GoodData = [];
  private TableData = [];
  totalPrice: number = 0;
  sumBuy: any = 0;
  sumPrice: any;
  goodType: Array<{id:number, name:string, chosen:boolean}>;
  goodList: Array<{
    name: string, id: number, isSelect: boolean, sumBuy: number, sumPrice: number,
    goods: Array<{ goodid: string, goodname: string, goodprice: number, goodimg: string, sumBuy: number, sumPrice: number, isbuy: boolean }>
  }>;
  tel: any;
  total: any = false;
  lastNum: number = 0;

  shoppingState = false;
  basket: any;

  orderList:any=[];
  orderdetail:any=[];
  flag:string;

  constructor(public navCtrl: NavController, public params: NavParams, public alertCtrl: AlertController,private http:HttpClient,private storage: Storage) {

    this.callBack = this.params.get('callback');
    this.floor = this.params.get('floor');
    this.tableNo = this.params.get('tableNo');
    this.tableid=this.params.get('tableid');
    this.sumCount = this.params.get('sumCount');
    this.goodname = this.params.get('goodname');
    this.goodprice = this.params.get('goodprice');
    this.status = this.params.get('status');
    this.flag=this.params.get('flag');

    this.goodType=[];
    this.goodList=[];
    this.basket=[];
    this.http.post(AppUrl.food.foodtype,{floorid:this.floor}).subscribe(data=>{
      let temp1:any=data;
      let temp:any=temp1.data;
      let type:any=temp[0];
      let food:any=temp[1];
      console.log(type);
      for(let array of type){
        this.goodType.push({
          id:array.id,
          name:array.foodtype,
          chosen:false
        });

        for(let ar of food){
          if(ar.foodtype==array.id){
            let k=this.goodList.findIndex(e=>e.id==ar.foodtype);
            if(k!=-1){
              this.goodList[k].goods.push({
                goodid: ar.id, goodname: ar.foodname, goodprice: ar.price, goodimg: '', sumBuy: 0, sumPrice: 0, isbuy: false
              });
            }else{
              this.goodList.push({
                name: array.foodtype, id: array.id, isSelect: false, sumBuy: 0, sumPrice: 0,goods:[{
                  goodid: ar.id, goodname: ar.foodname, goodprice: ar.price, goodimg: '', sumBuy: 0, sumPrice: 0, isbuy: false
                }]
              })
            }
          }
        }
      }
      console.log(this.goodType);
      console.log(this.goodList);
      if(this.goodType.length>0){
        this.goodType[0].chosen=true;
      }
      if(this.goodList.length>0){
        this.tel = this.goodList[0].goods;
      }

      this.basket = {allPrice: 0, goodslist: this.goodList};
    });

    // this.goodList = [
    //   {
    //     name: '推荐', id: '0', isSelect: false, sumBuy: 0, sumPrice: 0, goods: [
    //       {
    //         goodid: '001',
    //         goodname: '乡村牛肉',
    //         goodprice: 33,
    //         goodimg: 'assets/imgs/food/乡村牛肉.jpg',
    //         sumBuy: 0,
    //         sumPrice: 0,
    //         isbuy: false
    //       },
    //     ]
    //   },
    //   {
    //     name: '凉菜', id: '1', isSelect: false, sumBuy: 0, sumPrice: 0, goods: [
    //       {
    //         goodid: '011',
    //         goodname: '凉拌黄瓜',
    //         goodprice: 11,
    //         goodimg: 'assets/imgs/food/凉拌黄瓜.png',
    //         sumBuy: 0,
    //         sumPrice: 0,
    //         isbuy: false
    //       },
    //     ]
    //   },
    //   {
    //     name: '主食', id: '2', isSelect: false, sumBuy: 0, sumPrice: 0, goods: [
    //       {
    //         goodid: '018',
    //         goodname: '米饭',
    //         goodprice: 3,
    //         goodimg: 'assets/imgs/food/米饭.png',
    //         sumBuy: 0,
    //         sumPrice: 0,
    //         isbuy: false
    //       },
    //     ]
    //   },
    //   {
    //     name: '小吃', id: '3', isSelect: false, sumBuy: 0, sumPrice: 0, goods: [
    //       {
    //         goodid: '019',
    //         goodname: '木瓜水',
    //         goodprice: 6,
    //         goodimg: 'assets/imgs/food/木瓜水.jpg',
    //         sumBuy: 0,
    //         sumPrice: 0,
    //         isbuy: false
    //       },
    //     ]
    //   },
    //   {
    //     name: '套餐', id: '4', isSelect: false, sumBuy: 0, sumPrice: 0, goods: [
    //       {
    //         goodid: '030',
    //         goodname: '四人套餐',
    //         goodprice: 168,
    //         goodimg: 'assets/imgs/food/双人餐.jpg',
    //         sumBuy: 0,
    //         sumPrice: 0,
    //         isbuy: false
    //       },
    //     ]
    //   },
    // ];

  }

  // ionViewWillEnter() {
  //   this.storage.get('GoodData').then(data1 => {
  //     this.GoodData = data1;
  //     console.info('桌名获取'+data1)
  //   });
  // }

  showGoods(i) {
    this.goodType[this.lastNum].chosen = false;
    this.lastNum = i;
    this.goodType[i].chosen = true;
    let k=this.goodList.findIndex(e=>e.id==this.goodType[i].id);
    this.tel = this.goodList[k].goods;
  }

  Settle() {

    this.navCtrl.push('CashdetailPage',{floor:this.floor,pagetitle:'收银'});


    // this.storage.get('TableData').then(data => {
    //   this.TableData = data;
    //   // switch(data.orderTable.tableSite)
    //   for (let tabledata of this.TableData) {
    //     let tmp = tabledata.tables.filter(e => e.tablename === this.tableNo);
    //     console.info('进1');
    //     for (let tmpSite of tmp) {
    //       console.info('进2');
    //       if (tmpSite.tableSite.name === this.tableSite.Idle.name) {
    //         this.Order();
    //         console.info('进点菜');
    //       }
    //       else if (tmpSite.tableSite.name === this.tableSite.used.name) {
    //         this.OrderAdd();
    //         console.info('进加菜');
    //       }
    //     }
    //   }
    // });
  }

  // Order() {
  //   if (this.totalPrice == 0) return;
  //   let data = [];
  //   // let data1 = [];
  //   for (let store of this.goodList) {
  //     let tmp = store.goods.filter(e => e.isbuy);
  //     if (tmp.length > 0) {
  //       let singlePrice = 0;
  //       for (let item of tmp) {
  //         singlePrice = item.sumPrice;
  //       }
  //
  //       this.storage.get('TableData').then(data1 => {
  //         this.TableData = data1;
  //         for (let storage of this.TableData) {
  //           let tmptable = storage.tables.filter(data1 => data1.tablename === this.tableNo);
  //           if (tmptable.length > 0) {
  //             for (let tableitem of tmptable) {
  //               tableitem.tableSite = this.tableSite.used;
  //               this.id = tableitem.id;
  //             }
  //           }
  //           // this.saveTableDataStorage();
  //           // this.navCtrl.pop();
  //           // console.log('打下GoodData' + this.TableData);
  //         }
  //       });
  //
  //       this.storage.get('GoodData').then(data => {
  //         this.GoodData = data;
  //         console.info(this.floor);
  //         this.GoodData[this.floor - 1].orderTable.push({
  //           id: this.id,
  //           tableNo: this.tableNo,
  //           tableSite: this.tableSite.used,
  //           goodsList: tmp,
  //           sumCount: this.totalPrice,
  //         });
  //         // this.saveGoodDataStorage();
  //         this.navCtrl.pop();
  //         console.log('打下GoodData' + this.GoodData);
  //       });
  //
  //
  //       console.info(data);
  //     }
  //   }
  //   this.print();
  // }

  // OrderAdd() {
  //   if (this.totalPrice == 0) return;
  //   let data = [];
  //   // let data1 = [];
  //   for (let store of this.goodList) {
  //     let tmp = store.goods.filter(e => e.isbuy);
  //     if (tmp.length > 0) {
  //       let singlePrice = 0;
  //       for (let item of tmp) {
  //         singlePrice = item.sumPrice;
  //
  //
  //         this.storage.get('TableData').then(data1 => {
  //           this.TableData = data1;
  //           for (let storage of this.TableData) {
  //             let tmptable = storage.tables.filter(data1 => data1.tablename === this.tableNo);
  //             if (tmptable.length > 0) {
  //               for (let tableitem of tmptable) {
  //                 this.id = tableitem.id;
  //               }
  //             }
  //             // this.saveTableDataStorage();
  //             // this.navCtrl.pop();
  //             // console.log('打下GoodData' + this.TableData);
  //           }
  //         });
  //
  //
  //         this.storage.get('GoodData').then(data => {
  //           this.GoodData = data;
  //           console.info(this.floor);
  //           for (let good of this.GoodData) {
  //             let tmptable = good.orderTable.filter(data2 => data2.tableNo === this.tableNo);
  //             if (tmptable.length > 0) {
  //               for (let tableitem of tmptable) {
  //                 let i = tableitem.goodsList;
  //                 tableitem.sumCount = tableitem.sumCount + item.sumPrice;
  //                 // this.GoodData[this.floor - 1].orderTable.push({
  //                 //   tableNo: this.tableNo,
  //                 //   tableSite: this.tableSite.used,
  //                 //   goodsList: tmp,
  //                 //   sumCount: this.totalPrice,
  //                 // });
  //                 // sumCount: this.totalPrice+ tableitem.sumCount,
  //                 // this.GoodData[this.floor - 1].orderTable[this.id -1].goodsList.push(tmp);
  //                 this.GoodData[this.floor - 1].orderTable[this.id - 1].goodsList.push({
  //                   goodname: item.goodname,
  //                   goodprice: item.goodprice,
  //                   sumBuy: item.sumBuy,
  //                   sumPrice: item.sumPrice,
  //                   isbuy: item.isbuy,
  //                 });
  //               }
  //             }
  //           }
  //           // this.saveGoodDataStorage();
  //           this.navCtrl.pop();
  //           console.log('打下GoodData' + this.GoodData);
  //         });
  //       }
  //
  //       console.info(data);
  //     }
  //   }
  //   this.print();
  // }

  add(item) {
    item.sumBuy++;
    item.isbuy = true;
    item.sumPrice = item.sumPrice + item.goodprice;
    this.totalPrice = this.totalPrice + item.goodprice;
    this.sumBuy++;
    this.basket.allPrice = this.basket.allPrice + item.goodprice;
    // console.log(item.sumPrice=item.sumPrice+item.goodprice);
  }

  // allSelect(){
  //   this.total=!this.total;
  //   if(this.total)
  //     this.goodList.forEach(e=>{
  //       e.isSelect=true
  //       e.goods.forEach(j=>{
  //         if(!j.isbuy){
  //           j.isbuy=true
  //           e.sumBuy=e.sumBuy+j.sumBuy;
  //           this.totalPrice=this.totalPrice+j.sumPrice;
  //         }
  //       });
  //     });
  // }

  print() {
    console.log('print`````>');
    let message: string;
    if (this.totalPrice > 0) {
      message = '成功发送后厨打印!';
    } else {
      message = '您没有点餐!';
    }
    let alert = this.alertCtrl.create({
      title: message,
      subTitle: '',
    });
    alert.addButton({
      text:'确定',
      handler:()=>{
        if(this.totalPrice > 0){
          //订单
          this.orderList={
            orderno:'', trandate:'', tableno:this.tableid, totalprice:this.basket.allPrice,
            printflag:'1', printtime:'', payflag:'', paytype:'', discounttype:'', discountrate:0.00, realpay:0.00, orderstatus:'0',orderType:0
          };
          //订单明细

          //点餐
          if(this.flag=='open'){
            this.http.post(AppUrl.food.foodorder,[this.orderList,this.orderdetail,'1']).subscribe(data=>{
              console.log(data);
              let temp:any=data;
              if(temp.code!=200){
                this.showAlert(temp.msg);
              }else{
                this.callBack(this.tableNo).then(()=>{
                  this.navCtrl.pop();
                });
              }
            });
          }else{
            //加菜
            this.http.post(AppUrl.food.addfood,[{tableno:this.tableid,totalprice:this.totalPrice},this.orderdetail]).subscribe(data=>{
                console.log(data);
              this.callBack(this.tableNo).then(()=>{
                this.navCtrl.pop();
              });
            });
          }
        }
      }
    });
    alert.present();
  }

  changeShoppingState() {
    this.shoppingState = !this.shoppingState;
  }

  //清空商品
  cleanAll() {
    this.basket.allPrice = 0;
    for (let good of this.goodList) {
      good.goods.forEach(e => {
        e.sumBuy = 0;
        e.sumPrice = 0;
        e.isbuy = false
      });
    }
    this.totalPrice = 0;
    this.sumBuy = 0;
    this.orderdetail=[];
  }

  //添加商品
  addGood(good) {
    console.info("加入商品：" + good.goodid)
    good.sumBuy++;
    good.sumPrice = good.sumPrice + good.goodprice;
    good.isbuy = true;
    this.totalPrice = this.totalPrice + good.goodprice;
    this.sumBuy++;
    this.basket.allPrice = this.basket.allPrice + good.goodprice;
    let index=this.orderdetail.findIndex(e=>e.foodid==good.goodid);
    console.log(index);
    if(index!=-1){
      this.orderdetail[index].num++;
      console.log('添加了1份已有的'+good.goodname);
      console.log(this.orderdetail[index].num);
    }else{
      console.log('添加了1份新的'+good.goodname);
      this.orderdetail.push({
        orderno:'',
        foodid:good.goodid,
        num:1
      });
    }
    console.log(this.orderdetail);
  }

  //去除商品
  reduceGood(good) {
    console.info("去除商品：" + good.goodid);
    let index=this.orderdetail.findIndex(e=>e.foodid==good.goodid);
    if (good.sumBuy > 0) {
      good.sumBuy--;
      good.sumPrice = good.sumPrice - good.goodprice;
      this.totalPrice = this.totalPrice - good.goodprice;
      this.sumBuy--;
      this.basket.allPrice = this.basket.allPrice - good.goodprice;

      if(index!=-1){
        this.orderdetail[index].num--;
      }
    }
    if (good.sumBuy == 0) {
      if(index!=-1){
        this.orderdetail.splice(index,1);
      }
      good.isbuy = false;
    }
  }

  showAlert(msg) {
    let alert = this.alertCtrl.create({
      title: '开台失败!',
      subTitle: msg,
      buttons: ['OK']
    });
    alert.present();
  }
}
